import { HttpParams, HttpHeaders } from '@angular/common/http'
import { IQueryParams } from '@shared/interfaces/queryParams'
import { omitEmptyValue } from 'app/utils/helpers'

/* 预处理请求参数, 去掉空参数，补充必须参数 */
export function preProcessParams(): MethodDecorator {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originMethod = descriptor.value
    descriptor.value = function(...obj) {
      const [params, ...rest] = obj
      if (!params.size) {
        params.size = 10
      }
      if (!params.page) {
        params.page = 1
      }
      const newParams = omitEmptyValue(params)
      if (!!rest[0]) return originMethod.call(this, newParams, ...rest)
      return originMethod.call(this, newParams)
    }
    return descriptor
  }
}

/* 生成 options */
// export function generateOptions(): MethodDecorator {
//   return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
//     const originMethod = descriptor.value
//     descriptor.value = function(params: IQueryParams) {
//       let hp = new HttpParams()
//       Object.keys(params).forEach(key => hp = hp.append(key, params[key]))
//       const options = {
//         params: hp,
//         withCredentials: true,
//       }
//       return originMethod.call(this, params, options)
//     }
//   }
// }

/* 自转义 : -> %2B */
export function encodeParams(): MethodDecorator {
  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originMethod = descriptor.value
    descriptor.value = function(...obj) {
      const [params] = obj
      let str = ''
      for (const key in params) {
        const sub = `${key}=${params[key]}&`.replace('+', '%2B')
        str += sub
      }
      str = str.substr(0, str.length - 1)
      return originMethod.call(this, ...obj, str)
    }
    return descriptor
  }
}
